<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>对象映射</title>
</head>

<body>
    <script>

        // 1、定义参数映射 paramsMapping
        let paramsMapping = [
            {
                // API参数名
                paramName: 'feeCode',
                // 表单字段名 
                formName: 'code',
                // 默认值
                defaultValue: '10000'
            }
        ];

        // 2、定义输入参数 enterParams
        let enterParams = [
            {
                param: 'code',
                paramName: 'code'
            },
            {
                param: 'name',
                paramName: 'name'
            }
        ];

        // 3、定义表单数据 formData
        let formData = {
            code: '123',
            name: '张三',
            time: '2021-10-01'
        };

        // 4、初始化映射结果 mappedData
        let mappedData = {}; // 空对象，用于存储映射结果

        // 5、构建参数映射对象 paramMappingObj
        let paramMappingObj = {};
        paramsMapping.forEach(mapping => {
            paramMappingObj[mapping.formName] = mapping;
        });

        // 6、处理输入参数并生成映射结果
        enterParams.forEach(paramObj => {
            const mapping = paramMappingObj[paramObj.param];
            console.log(mapping); // 输出：{paramName: "feeCode", formName: "code", defaultValue: "10000"}
            if (mapping) {
                const code = mapping.paramName;
                const name = mapping.paramName;
                console.log(code, name); // 输出：feeCode feeCode
                if (formData[paramObj.param]) {
                    mappedData[code] = formData[paramObj.param];
                    mappedData[name] = formData[paramObj.param];
                    console.log(mappedData); // 输出：{feeCode: "123", name: "123"}
                } else {
                    mappedData[mappedParam] = mapping.defaultValue || '';
                }
            } else {
                // 如果没有映射关系，则直接拷贝参数
                mappedData[paramObj.param] = formData[paramObj.param] || '';
            }
        });

        console.log(mappedData);

    </script>
</body>

</html>